package cn.gtlc.myUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileDownloader {

    public static void main(String[] args) {
        String fileURL = "http://223.82.48.52:8081/shipin/m3u8/fojinniansong/w3008xk787k";
        String saveDir = "D:/down";
        String fileName = "w3008xk787k";

        try {// all = 504
            for (int i=101; i<=504; i++) {
                downloadFile(fileURL+i+".ts", saveDir, fileName+i+".ts");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void downloadFile(String fileURL, String saveDir, String fileName) throws IOException {
        URL url = new URL(fileURL);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        int responseCode = httpConn.getResponseCode();

        // 检查是否成功建立连接
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 读取文件流
            InputStream inputStream = httpConn.getInputStream();

            // 指定保存文件路径和名称
            File saveFilePath = new File(saveDir + File.separator + fileName);

            // 如果保存目录不存在则创建
            if (!saveFilePath.getParentFile().exists()) {
                saveFilePath.getParentFile().mkdirs();
            }

            // 写入文件流到磁盘
            OutputStream outputStream = new FileOutputStream(saveFilePath);

            int bytesRead = -1;
            byte[] buffer = new byte[1024];
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            outputStream.close();
            inputStream.close();

            System.out.println("文件下载成功");
        } else {
            System.out.println("无法连接到提供下载的服务器，错误代码为：" + responseCode);
        }
    }
}